<script setup lang="ts">
defineOptions({
  name: "supplyBottle"
});

import { ref, onMounted, onUnmounted, markRaw, getCurrentInstance, provide } from "vue";
import { queryFillingManageList, deleteFillingManage, importFillingManageData } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { Edit, Delete } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useTableCloumns, useSearchOption } from "../hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import add from "./add.vue";
import importBottle from "./importBottle.vue";
import { useMessageBox } from "@/hooks/useCommon";

interface Props {
  //  1 在供气瓶  2 返库气瓶  3 过期气瓶
  type: 1 | 2 | 3;
}

const props = withDefaults(defineProps<Props>(), { type: 1 });

provide("bottleType", props.type);

const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption());
const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns());
const params = ref<any>({});
// 弹框类型 add 新增   edit 编辑
const addType = ref<"add" | "edit">("add");
const bottleId = ref<string>("");
const addDialogTableVisible = ref<boolean>(false);
const importBottleVisible = ref<boolean>(false);

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: "GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_EDITBTN",
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope)
  },
  {
    content: "删除",
    auth: "GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_DELETEBTN",
    icon: markRaw(Delete),
    type: "danger",
    click: (scope: any) => del(scope)
  }
];

let defaultParams: any = {
  // 1：在供，2：返库，3：过期
  // lifeCycle: props.type
};
let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

const sortChangeHandler = ({ column, order }: CommonTable.SortParams) => {
  const { property: orderBy = "" } = column;
  // ascending  descending
  const isAsc = order === "ascending" ? true : order === "descending" ? false : true;
  currentParams["orderBy"] = orderBy;
  currentParams["isAsc"] = isAsc;
  if (!order) {
    currentParams.orderBy && delete currentParams.orderBy;
    currentParams.isAsc && delete currentParams.isAsc;
  }
  updateParams();
};

// const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
//   const style = {};
//   if (columnIndex === 3) {
//     style["text-align"] = "center";
//   }
//   return style;
// };

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const addFn = () => {
  bottleId.value = "";
  addType.value = "add";
  addDialogTableVisible.value = true;
};

const { proxy }: any = getCurrentInstance();

const downloadFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/tankTruckFilling/downloadTemplate";
  proxy.download("post", url);
}, delay);

const batchImportFn = () => {
  importBottleVisible.value = true;
};

const batchExportFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/tankTruckFilling/exportData";
  const params = commonTableRef.value.getParams();
  proxy.download("post", url, params);
  PxMessageBox.alert("正在导出您筛选的数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "批量导出", {
    confirmButtonText: "我知道了"
  });
}, delay);

const edit = scope => {
  const {
    row: { id = "" }
  } = scope;
  bottleId.value = id;
  addType.value = "edit";
  addDialogTableVisible.value = true;
};

const del = async scope => {
  const {
    row: { tankTruckNo = "", id = "" }
  } = scope;
  const msg = `确定要删除槽车 ${tankTruckNo}吗？`;
  useMessageBox("delete", msg, async () => {
    await deleteFillingManage(id);
    PxMessage.success("删除成功！");
    commonTableRef.value.queryTableData();
  });
};

const submitHandler = (flag: boolean = false) => {
  const message = flag ? "导入成功" : addType.value === "add" ? "创建成功" : "编辑成功";
  PxMessage.success(message);
  commonTableRef.value.queryTableData();
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="all-orders">
    <div class="all-orders-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        :row-num="4"
        :operation-span="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="all-orders-btns">
      <px-button v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_ADDBTN'" type="primary" @click="addFn">新增</px-button>
      <px-button v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_DOWNLOADBTN'" type="primary" plain @click="downloadFn">模板下载</px-button>
      <px-button v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_IMPORTBTN'" type="primary" plain @click="batchImportFn">批量导入</px-button>
      <px-button v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFMANAGE_EXPORTBTN'" type="primary" plain @click="batchExportFn">批量导出</px-button>
    </div>
    <div ref="objectModelTableRef" class="all-orders-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :axiosApi="queryFillingManageList"
        :params="params"
        @sort-change="sortChangeHandler"
      />
    </div>
    <add v-if="addDialogTableVisible" :id="bottleId" v-model="addDialogTableVisible" :type="addType" @submit="submitHandler" />
    <importBottle v-if="importBottleVisible" v-model="importBottleVisible" :uploadApi="importFillingManageData" @submit="submitHandler(true)" />
  </div>
</template>

<style lang="scss" scoped>
.all-orders {
  width: 100%;
  background-color: #fff;

  .all-orders-search {
    width: 100%;
  }

  .all-orders-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .all-orders-table {
    margin-top: 16px;
  }
}
</style>
